﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThreeByte.TaskModel;
using System.ComponentModel;
using ThreeByte.ActiveDeck.Config;
using ThreeByte.ActiveDeck.Service;
using System.Windows.Controls;
using ThreeByte.ActiveDeck.Content;
using System.Windows.Threading;
using System.Xml.Linq;
using ThreeByte.ActiveDeck.Data;
using System.Diagnostics;
using System.IO;
using log4net;

namespace ThreeByte.ActiveDeck.AddIn.Config
{
    public class DeleteResourcesTask : AsyncTaskBase
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(RetrieveResourcesTask));

        private string PresentationID;
        private WebServiceClient Client;
        public List<Guid> ResourcesToDelete { get; private set; }
        private int _totalResources;
        private static readonly int TAKE_COUNT = 100;


        public DeleteResourcesTask(string presentation, WebServiceClient client, List<Guid> resources) {
            PresentationID = presentation;
            Client = client;
            Name = string.Format("Deleting Unused Resources...");
            ResourcesToDelete = resources.ToList();
            _totalResources = ResourcesToDelete.Count;
        }

        protected override void Run(BackgroundWorker bw, DoWorkEventArgs e) {
            
            while(ResourcesToDelete.Count > 0) {
                if(bw.CancellationPending) {
                    return;
                }
                Status = string.Format("Remaining resources...{0}", ResourcesToDelete.Count);
                int progress = ((_totalResources - ResourcesToDelete.Count) * 100) / _totalResources;
                bw.ReportProgress(progress);

                List<Guid> idsToDelete = new List<Guid>();
                for(int i = 0; (i < TAKE_COUNT) && (i < ResourcesToDelete.Count); i++) {
                    idsToDelete.Add(ResourcesToDelete[i]);
                }
                Client.DeleteResources(PresentationID, idsToDelete);
                foreach(Guid g in idsToDelete) {
                    ResourcesToDelete.Remove(g);
                }
            }

            bw.ReportProgress(100);
            Status = "Complete"; 

        }

    }
}
